package com.violet.common.util;

import cn.hutool.json.JSONUtil;
import com.violet.common.constant.business.CodeEnum;
import com.violet.common.response.Result;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: wqf
 * @Date: 2023/07/09
 * @Description:
 */
public class ResponseUtil {

    /**
     * 方法描述: 错误消息响应
     *
     * @param response 响应体
     * @author wqf
     * @date 2023/7/9 00:05
     */
    public static void errorResponse(HttpServletResponse response,
                                     CodeEnum codeEnum,
                                     String errorMsg,
                                     HttpStatus httpStatus) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try (ServletOutputStream ous = response.getOutputStream()) {
            Result<Object> responseData = Result.failure(codeEnum.getCode(), errorMsg);
            response.setStatus(httpStatus.value());
            ous.write(JSONUtil.toJsonStr(responseData).getBytes(StandardCharsets.UTF_8));
        }
    }
}
